/**
 * This servlet is based on the following code: 
 * http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
 */
package sanger;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload extends HttpServlet {

    private File destinationDir;
    private String prefix;
    private List<String> params;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);


        destinationDir = new File(Constants.UPLOAD_DIR);

        if (!destinationDir.isDirectory()) {
            throw new ServletException(Constants.UPLOAD_DIR + " is not a directory");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //not authenticated
        Utilities.logOrRedir(request.getSession(), request, response);

        //removed a _
        prefix = (String) request.getSession().getAttribute("uname");
        params = new ArrayList<String>();



        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        out.println("<h1>Please choose a file to upload</h1>");

        out.println();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 MB

        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(destinationDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            /*
             * Parse the request
             */
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                if (item.isFormField()) {

                    //PoC - no validation for email
                    //Assures we have the parameters at the same position in the
                    //list -> easy extraction at a later time.
                    if (item.getFieldName().equals("email1")) {
                        params.add(0, item.getString());
                    } else if (item.getFieldName().equals("email2")) {
                        params.add(1, item.getString());
                    } else if (item.getFieldName().equals("hashValue")) {
                        params.add(2, item.getString());
                    } else if (item.getFieldName().equals("readType")) {
                        params.add(3, item.getString());
                    }

                    //out.println(item.getFieldName() + " " + item.getString());

                } else {

                    //upload the file to the local disk
                    File file = new File(destinationDir, prefix + item.getName());
                    item.write(file);

                    //allocate new thread to do all background processing
                           
                    new Thread(Utilities.Process(file.getAbsolutePath(), prefix, prefix + item.getName(), params)).start();
                    
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                }

            }
            out.close();
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }
    }
}
